﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AVIS.OutBound.Orders.Dto;
using AVIS.OutBound.ThirdOrders.Dto;
using AVIS.OutBound.BookOrders;
using Abp.ObjectMapping;
using System.Configuration;
using AVIS.OutBound.Orders;
using Abp.UI;
using AVIS.OutBound.Regions;
using AVIS.OutBound.Countrys;
using AVIS.OutBound.Stores;

namespace AVIS.OutBound.ThirdOrders
{
    /// <summary>
    /// 第三方订单的应用服务类，如：AA接机订单，游友订单（现在修改为漫游包Wifi订单）
    /// </summary>
    public class ThirdOrderAppService : OutBoundAppServiceBase, IThirdOrderAppService
    {
        #region 构造函数
        private readonly IYouYouOrderManager _youyouOrderManager;
        private readonly IAAOrderManager _aaOrderManager;
        private readonly IBookOrderManager _bookOrderManager;
        private readonly IObjectMapper _objectMapper;
        private readonly IOrderManager _orderManager;
        private readonly IStoreManager _storeManager;
        private readonly IRegionManager _regionManager;
        private readonly ICountryManager _countryManager;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ThirdOrderAppService(
              IYouYouOrderManager youyouOrderManager,
              IAAOrderManager aaOrderManager,
              IOrderManager orderManager,
              IBookOrderManager bookOrderManager,
              IObjectMapper objectMapper,
              IStoreManager storeManager,
              IRegionManager regionManager,
              ICountryManager countryManager)
        {
            _youyouOrderManager = youyouOrderManager;
            _aaOrderManager = aaOrderManager;
            _orderManager = orderManager;
            _bookOrderManager = bookOrderManager;
            _objectMapper = objectMapper;
            _storeManager = storeManager;
            _regionManager = regionManager;
            _countryManager = countryManager;
        }
        #endregion

        /// <summary>
        /// 查询指定预订单ID的第三方增值服务接口
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public List<ThirdProductDto> CarProductsByOrderId(OrderIdInput input)
        {
            var products = new List<ThirdProductDto>();

            // 获取订单信息（预定单）
            var bookOrder = _bookOrderManager.GetBookOrder(input.orderId);

            // 添加游友产品（现在修改为漫游包Wifi产品）
            var youyouConfig = ConfigurationManager.AppSettings["YouYou_AllowAAN"] ?? "";
            if (IsAllowThirdOrder(bookOrder.IATA, bookOrder.AWD, youyouConfig))
            {
                var productWifi = _youyouOrderManager.GetProducts(bookOrder.CountryCode ?? "US");
                if (productWifi != null)
                {
                    var wifiRemark = ConfigurationManager.AppSettings["YouYouRemark"] ?? "";
                    products.Add(new ThirdProductDto
                    {
                        Name = productWifi.Name,
                        Title = "Avis赠送您" + productWifi.Title,
                        UnitPrice = (productWifi.Discount / 100).ToString(),
                        UnitName = "天",
                        CurrencyCode = "元",
                        Remark = string.Format(wifiRemark, GetRentalLength(bookOrder.RentalLength)),
                        ProductId = productWifi.ID,
                        Type = OutBoundConsts.THIRD_PRODUCT_TYPE_WIFI
                    });
                }
            }

            // 添加AA接机产品
            var aaConfig = ConfigurationManager.AppSettings["AA_AllowAAN"] ?? "";
            if (IsAllowThirdOrder(bookOrder.IATA, bookOrder.AWD, aaConfig))
            {
                var aaRemark = ConfigurationManager.AppSettings["AARemark"] ?? "";
                products.Add(new ThirdProductDto
                {
                    Name = "国内接机服务",
                    Title = "招行赠送您国内接机服务",
                    UnitPrice = "0",
                    UnitName = "1次",
                    CurrencyCode = "元",
                    Remark = aaRemark,
                    ProductId = "0",
                    Type = OutBoundConsts.THIRD_PRODUCT_TYPE_AA
                });
            }

            return products;
        }

        /// <summary>
        /// 获取指定订单号的第三方增值服务订单信息
        /// </summary>
        /// <param name="orderNo">Avis订单号</param>
        /// <returns></returns>
        public List<ThirdOrderDto> GetThirdOrders(string orderNo)
        {
            var list = new List<ThirdOrderDto>();

            // AA接机订单
            var aaOrder = _aaOrderManager.GetDBOrder(orderNo);
            if (aaOrder != null)
            {
                list.Add(new ThirdOrderDto
                {
                    Type = OutBoundConsts.THIRD_PRODUCT_TYPE_AA,
                    ID = aaOrder.Id.ToString(),
                    ThirdOrderNo = (aaOrder.AAStatus != 6) ? orderNo : "", // 因为AANo不回填了，故用Avis订单号来代替
                    ProductName = "国内接机服务",
                });
            }

            // 漫游包Wifi订单
            var wifiOrder = _youyouOrderManager.GetDBOrder(orderNo);
            if (wifiOrder != null)
            {
                list.Add(new ThirdOrderDto
                {
                    Type = OutBoundConsts.THIRD_PRODUCT_TYPE_WIFI,
                    ID = wifiOrder.Id.ToString(),
                    ThirdOrderNo = wifiOrder.Sn,
                    ProductId = wifiOrder.ProductID.ToString(),
                    ProductName = wifiOrder.ProductName,
                });
            }

            return list;
        }

        /// <summary>
        /// 保存AA接机预订订单
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public bool SaveAAOrder(AAOrderInput input)
        {
            // 判断Avis订单是否已经取消了
            var order = _orderManager.GetDBOrder(input.ReservationNumber);
            if (order == null || order.IsCancel)
            {
                throw new UserFriendlyException($"无效的订单号（{input.ReservationNumber}）或订单已经取消");
            }

            var aaOrder = _objectMapper.Map<AAOrder>(input);
            return _aaOrderManager.UpdateOrderToCompleted(aaOrder);
        }

        /// <summary>
        /// 获取指定Avis订单号的AA接机预订单提交前信息
        /// </summary>
        /// <param name="orderNo">Avis订单号</param>
        /// <returns></returns>
        public AAOrderOutput GetAAOrderByOrderNo(string orderNo)
        {
            var order = _orderManager.GetDBOrder(orderNo);
            if (order == null || order.IsCancel)
            {
                throw new UserFriendlyException($"无效的订单号（{orderNo}）或订单已经取消");
            }

            return _objectMapper.Map<AAOrderOutput>(order);
        }

        /// <summary>
        /// 获取指定Avis订单号的游友订单提交前信息（现在修改为漫游包Wifi订单）
        /// </summary>
        /// <param name="orderNo">Avis订单号</param>
        /// <param name="productId">产品ID</param>
        /// <returns></returns>
        public YouYouOrderOutput GetYouYouOrderByOrderNo(string orderNo, string productId)
        {
            var order = _orderManager.GetDBOrder(orderNo);
            if (order == null || order.IsCancel)
            {
                throw new UserFriendlyException($"无效的订单号（{orderNo}）或订单已经取消");
            }

            var youyouOrder = _objectMapper.Map<YouYouOrderOutput>(order);
            youyouOrder.ProductID = productId;

            //// 处理国家Code
            //if (string.IsNullOrWhiteSpace(order.CountryCode) && !string.IsNullOrEmpty(order.PickUpStoreCode))
            //{
            //    var pickUpStore = _storeManager.GetStoreByCode(order.PickUpStoreCode);
            //    if (pickUpStore != null)
            //    {
            //        var region = _regionManager.GetRegion(pickUpStore.RegionCode);
            //        if (region != null)
            //        {
            //            var country = _countryManager.GetCountry(region.CountryCode, region.CountryName);
            //            youyouOrder.CountryCode = country?.Code;
            //        }
            //    }
            //}

            // 处理加密Key
            var rentalLength = GetRentalLength(order.RentalLength);
            var keymi = $"avis{youyouOrder.OrderNo}{youyouOrder.PickupDateTime.ToString("yyyy/MM/dd HH:mm")}{youyouOrder.ReturnDateTime.ToString("yyyy/MM/dd HH:mm")}{rentalLength}youyou";
            var key = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(keymi, "MD5");
            youyouOrder.Key = key;

            return youyouOrder;
        }

        /// <summary>
        /// 通过第三方接口获取游友订单信息（现在修改为漫游包Wifi订单）
        /// </summary>
        /// <param name="orderNo">Avis订单号</param>
        /// <returns></returns>
        public string GetYouYouOrder(string orderNo)
        {
            var result = _youyouOrderManager.GetOrder(orderNo);
            return result;
        }

        /// <summary>
        /// 获取指定Avis订单号的AA接机订单详情
        /// </summary>
        /// <param name="orderNo">Avis订单号</param>
        /// <returns></returns>
        public AAOrderDetailOutput GetAAOrder(string orderNo)
        {
            var aaOrder = _aaOrderManager.GetDBOrder(orderNo);
            if (aaOrder == null)
            {
                throw new UserFriendlyException($"无效的订单号：{orderNo}");
            }

            return _objectMapper.Map<AAOrderDetailOutput>(aaOrder);
        }


        /// <summary>
        /// 判断第三方增值服务是否启用
        /// </summary>
        /// <param name="aan">aan号</param>
        /// <param name="awd">AWD号</param>
        /// <param name="config">配置文件</param>
        /// <returns></returns>
        private bool IsAllowThirdOrder(string aan, string awd, string config)
        {
            if (string.IsNullOrWhiteSpace(aan))
            {
                return false;
            }

            var dic = GetConfigDictionary(config);
            if (dic.ContainsKey(aan))
            {
                // 判断AWD是否为空，如果为空，则表示所有的AWD都有效
                if (dic[aan].Length == 1 && dic[aan][0] == string.Empty)
                {
                    return true;
                }
                if (dic[aan].Contains(awd))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 解析配置数据（启用的AAN和AWD号，其中AWD号可以为空，格式：[AAN1],[AWD1]^[AWD2];[AAN2],[AWD3]^[AWD4]）
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        private Dictionary<string, string[]> GetConfigDictionary(string config)
        {
            var dic = new Dictionary<string, string[]>();
            var listAAN = config.Split(";；".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in listAAN)
            {
                var aan2awd = item.Split(",，".ToCharArray());
                if (aan2awd.Length == 2)
                {
                    dic.Add(aan2awd[0], aan2awd[1].Split(OutBoundConsts.SysSeparator.ToCharArray()));
                }
            }

            return dic;
        }

        /// <summary>
        /// 获取租期
        /// </summary>
        /// <returns></returns>
        private int GetRentalLength(int RentalLength)
        {
            // 超过15天按15天计算
            var days = RentalLength > 15 ? 15 : RentalLength;
            return days;
        }
    }
}
